<template>
  <div class="container">


    <div class="shopping-cart">
      <el-table
          ref="multipleTable"
          :data="cartItems"
          @selection-change="handleSelectionChange"
          style="width: 100%"
      >
        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column label="商品信息" min-width="300">
          <template slot-scope="scope">
            <div class="product-info">
              <el-image
                  :src="scope.row.productPic"
                  :preview-src-list="[scope.row.productPic]"
                  style="width: 80px; height: 80px"
              ></el-image>
              <span class="product-name">{{ scope.row.productName }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="spec" label="规格" width="150">
          <template #default="{row,$index}">
            {{ skuData(row) }}
          </template>
        </el-table-column>

        <el-table-column label="单价" width="150">
          <template slot-scope="scope">
            <span>¥{{ scope.row.price }}</span>
          </template>
        </el-table-column>

        <el-table-column label="数量" width="150" align="center">
          <!--            <el-input-number-->
          <!--                v-model="scope.row.quantity"-->
          <!--                :min="1"-->
          <!--                size="small"-->
          <!--                @change="handleQuantityChange(scope.row)"-->
          <!--            ></el-input-number>-->
          <template #default="{ row, $index }">
            <el-button type="mini" icon="el-icon-minus" circle @click="minusNumber(row)"/>
            <span style="margin: 0 5px">{{ row.quantity }}</span>
            <el-button type="mini" icon="el-icon-plus" circle @click="addNumber(row)"/>
          </template>
        </el-table-column>

        <el-table-column label="小计" width="150">
          <template slot-scope="scope">
            <span class="subtotal">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button
                type="text"
                class="delete-btn"
                @click="handleDelete(scope.row)"
                size="small"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="cart-footer">
        <div class="footer-left">
          <el-button size="small" @click="handleBatchDelete">批量删除</el-button>
        </div>
        <div class="footer-right">
          <div class="service-info">
            <el-tag size="small" type="info">以旧换新 1件</el-tag>
            <el-tag size="small" type="info">自动服务 1件</el-tag>
          </div>
          <div class="total-amount">
            支付金额：<span class="amount">¥{{ totalAmount }}</span>
          </div>
          <el-button type="primary" @click="handleCheckout">现在结算</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {addOne} from "@/api/cart/cart";

export default {
  name: 'ShoppingCart',
  data() {
    return {
      cartItems: [],
      selectedItems: []
    }
  },
  computed: {
    totalAmount() {
      return this.selectedItems.reduce((sum, item) => {
        return sum + (item.price * item.quantity)
      }, 0)
    },

  },
  mounted() {
    this.getMyCartList()
  },
  methods: {
    //减一
    minusNumber(row) {
      this.$api.cart.minusOne(row.id).then(res => {
        if (res.code == 200) this.getMyCartList()
      })
    },
    addNumber(row) {
      this.$api.cart.addOne(row.id).then(res => {
        if (res.code == 200) this.getMyCartList()
      })
    },
    skuData(row) {
      if (row.productAttr == null || row.productAttr == '') {
        return "单卖无规格";
      }
      let data = JSON.parse(row.productAttr)
      return data.map(item => {
        return item.key + ":" + item.value
      }).join(";")
    },
    getMyCartList() {
      this.$api.cart.getCartList().then(res => {
        if (res.code == 200) {
          this.cartItems = res.data
        }
      })
    },
    handleSelectionChange(val) {
      this.selectedItems = val
    },
    handleQuantityChange(row) {
      // 可以在这里添加数量变化后的处理逻辑
      console.log('数量变化:', row)
    },
    handleDelete(row) {
      this.$confirm('确认删除该商品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.cart.deleteCart([row.id].join("")).then(res => {
          if (res.code == 200) {
            this.getMyCartList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleBatchDelete() {
      if (this.selectedItems.length === 0) {
        this.$message.warning('请先选择要删除的商品')
        return
      }
      this.$confirm(`确认删除选中的${this.selectedItems.length}件商品?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids=[]
        this.selectedItems.forEach(item=>{
          ids.push(item.id)
        })
        this.$api.cart.deleteCart(ids.join(",")).then(res => {
          if (res.code == 200) {
            this.getMyCartList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    moveToWishlist(row) {
      this.$message.success('已移入收藏夹')
      // 实现移入收藏夹的具体逻辑
    },
    handleCheckout() {
      if (this.selectedItems.length === 0) {
        this.$message.warning('请先选择要结算的商品')
        return
      }
      this.$router.push({path:"/submitOrder",query:{list:JSON.stringify(this.selectedItems)}})
    }
  }
}
</script>

<style scoped>
.shopping-cart {
  padding: 20px;
  background: #fff;
  border: 1px solid gainsboro;
  max-height: 800px;
  overflow: auto;
  margin: 10px 0;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.product-name {
  font-size: 14px;
  color: #333;
}

.cart-footer {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.service-info {
  display: flex;
  gap: 10px;
}

.total-amount {
  font-size: 14px;
}

.amount {
  color: #ff4d4f;
  font-size: 20px;
  font-weight: bold;
}

.delete-btn {
  color: #ff4d4f;
}

/* 覆盖Element UI的一些默认样式 */
:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-tag) {
  margin-right: 8px;
}
</style>